package com.rui1024.servlet;

import com.rui1024.dao.UserDao;
import com.rui1024.dao.impl.UserDaoImpl;
import com.rui1024.pojo.User;
import com.rui1024.util.JDBCUtil;
import com.rui1024.util.PropertiesUtil;
import com.rui1024.util.StringUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.UUID;


public class UserServlet extends HttpServlet {

    JDBCUtil jdbcUtil = new JDBCUtil();
    UserDao userDao=new UserDaoImpl();


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        HttpSession session = req.getSession();

        String action = req.getParameter("action");
        if("preSave".equals(action)){
            this.userPreSave(req,resp);
        }else{
            try {
                this.userSave(req,resp);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void userPreSave(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setAttribute("mainPage","user/userPreSave.jsp");
        req.getRequestDispatcher("mainTemp.jsp").forward(req,resp);
    }

    public void userSave(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("currentUser");

        //使用相对路径，可以上传后可以直接显示；使用绝对路径，需要重启项目才可以显示
        String uploadPath = this.getServletContext().getRealPath("/static/userImages/");

        List<FileItem> fileItems=null;
        fileItems = upload.parseRequest(req);
        for (FileItem fileItem : fileItems) {
            if(fileItem.isFormField()){
                String fieldName = fileItem.getFieldName();
                if("nickName".equals(fieldName)){
                    user.setNickName(fileItem.getString("utf-8"));
                }
                if("mood".equals(fieldName)){
                    user.setMood(fileItem.getString("utf-8"));
                }
            }else{
                String name = fileItem.getName();
                //未选择图片的情况，则还使用之前的图片
                if(StringUtil.isEmpty(name)){
                    user.setImageName(user.getImageName().substring(user.getImageName().lastIndexOf("/")+1));
                } else{
                    String uuidPath = UUID.randomUUID().toString();
                    //新的文件名：abcefghijk.jpg
                    String uploadFileName=uuidPath+"."+name.substring(name.lastIndexOf(".")+1);
                    user.setImageName(uploadFileName);
                    //文件完整的上传路径：E:/idea_project/Personal/static/userImages/abcefghijk.jpg
                    String uploadFilePath=PropertiesUtil.getValue("uploadFilePath")+uploadFileName;
                    System.out.println("新的文件名===================》"+uploadFileName);
                    System.out.println("文件完整的上传路径===================》"+uploadFilePath);
                    fileItem.write(new File(uploadFilePath));
                }
            }

        }
        Connection con=null;
        try {
            con= jdbcUtil.getCon();
            int i = userDao.userUpdate(con, user);
            if(i>0){
                user.setImageName(PropertiesUtil.getValue("imageFile")+user.getImageName());
                session.setAttribute("currentUser",user);
                req.getRequestDispatcher("main?all=true").forward(req,resp);
            }else{
                req.setAttribute("currentUser",user);
                req.setAttribute("error","保存失败！");
                req.setAttribute("mainPage","user/userPreSave.jsp");
                req.getRequestDispatcher("mainTemp.jsp").forward(req, resp);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                jdbcUtil.closeCon(con);
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
